<template>
  <div class="personnel-entry-exit-application bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">车辆进出管理</h2>


    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchApplications" @reset="resetSearch" />
    </div>


    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
     
      <button @click="exportData(applications, '车辆进出管理', selectedIds)" class="btn btn-secondary">导出</button>
    </div>


    <!-- Data Table -->

    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedApplications" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="LICENSE_PLATE" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_VEHICLES_TYPE" label="车辆类型" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="PARKING_NAME" label="停车场" header-align="center" align="center">
          <!-- <template #default="scope">
            <div v-for="(item) in cheboxname(scope.row.AUTHORITY_AREA)" :key="item">
              {{ item }}
            </div>
          </template> -->
        </el-table-column>
        <el-table-column prop="IN_AT" label="入场时间" header-align="center" align="center">
          <template #default="scope">
            <div>{{ scope.row.IN_AT != null ? dayjs(scope.row.IN_AT).format('YYYY-MM-DD HH:mm:ss') : '' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="EXIT_AT" label="出场时间" header-align="center" align="center">
          <template #default="scope">
            <div>{{ scope.row.EXIT_AT != null ? dayjs(scope.row.EXIT_AT).format('YYYY-MM-DD HH:mm:ss') : '' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_PHONE" label="联系方式" header-align="center" align="center"></el-table-column>
        <!-- <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editApplication(scope.row)" link>编辑</el-button>
          </template>
        </el-table-column> -->
      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="applications.length" :tableData="applications" @alltabledata="alltabledata" />

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="isDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'" width="650" destroy-on-close align-center>
      <form @submit.prevent="handleSubmit">
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">

            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">车牌号码</label>
              <input type="text" id="staffCode" v-model="formData.STAFF_CODE" required class="input">
            </div>
            <div>
              <label for="staffName" class="block text-sm font-medium text-muted-foreground">车辆类型</label>

              <select id="staffGender" v-model="formData.STAFF_GENDER" required class="input">
                <option value="男">男</option>
                <option value="女">女</option>
              </select>

            </div>
            <div>
              <label for="idCard" class="block text-sm font-medium text-muted-foreground">停车场</label>
              <input type="text" id="idCard" v-model="formData.ID_CARD" required class="input">
            </div>
            <div>
              <label for="staffGender" class="block text-sm font-medium text-muted-foreground">入场时间</label>
              <input type="text" id="TELEPHONE" v-model="formData.TELEPHONE" required class="input">
            </div>
            <div>
              <label for="TELEPHONE" class="block text-sm font-medium text-muted-foreground">出场时间</label>
              <input type="text" id="staffName" v-model="formData.STAFF_NAME" required class="input">
            </div>
            <div>
              <label for="staffGender" class="block text-sm font-medium text-muted-foreground">驾驶员姓名</label>
              <input type="text" id="TELEPHONE" v-model="formData.TELEPHONE" required class="input">
            </div>
            <div>
              <label for="staffGender" class="block text-sm font-medium text-muted-foreground">联系方式</label>
              <input type="text" id="TELEPHONE" v-model="formData.TELEPHONE" required class="input">
            </div>
          </div>
        </div>

        <div class="mt-6 flex justify-end space-x-2">
          <button type="button" @click="closeDialog" class="btn btn-secondary">取消</button>
          <button type="submit" class="btn btn-primary">确认</button>
        </div>
      </form>
    </el-dialog>





  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue'
import axios from 'axios'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()

import { dayjs } from "element-plus"
import { exportData } from '#/utils/exportfile.js'
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/hazardous-vehicle-review'
})

const search = ref({
  LICENSE_PLATE: '',
  DRIVER_NAME: '',
})
const formItems = ref([
  {
    label: '车牌号码:',
    model: 'LICENSE_PLATE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },


])
const loading = ref(false)
const applications = ref([])
const selectAll = ref(false)
const isDialogOpen = ref(false)

const isEditing = ref(false)
const formData = ref({})
const viewingItem = ref(null)
const displayedApplications = ref([])
const alltabledata = (data) => {

  displayedApplications.value = data
}
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const rowKey = (row) => row.ID // 设置行的唯一标识

const selectedIds = ref([])
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const checkarr = ref([])
const searchApplications = async () => {
  displayedApplications.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/pass/search`, { params: search.value })
    const check = await axios.get(`${apiBaseUrl.value}/area`)

    checkarr.value = check.data
    applications.value = response.data.map(app => ({ ...app, selected: false }))
    updateSelectAllState()
  } catch (error) {
    console.error('搜索申请失败:', error)
    alert('搜索申请失败: ' + (error.response?.data?.message || error.message))
  }
}
const cheboxname = (item) => {
  let name = []
  if (item != undefined) {
    name = JSON.parse(item)
  }

  const result = name.map(parkingCode =>
    checkarr.value.find(item => item.PARKING_CODE === parkingCode)
  ).filter(item => item !== undefined).map(item => item.PARKING_NAME + "/" + item.PARKING_AREA)
  console.log(result)

  return result
}



const resetSearch = () => {
  search.value = {
    LICENSE_PLATE: '',
    DRIVER_NAME: '',
  }
  searchApplications()
}

const openAddDialog = () => {
  isDialogOpen.value = true
  isEditing.value = false
  formData.value = {}
}

const closeDialog = () => {
  isDialogOpen.value = false
}

const handleSubmit = async () => {
  try {
    if (isEditing.value) {
      await axios.put(`${apiBaseUrl.value}/${formData.value.ID}`, formData.value)

    } else {
      await axios.post(`${apiBaseUrl.value}`, formData.value)

    }
    alert('提交成功')
    closeDialog()
    await searchApplications()
  } catch (error) {
    console.error('提交申请失败:', error)
    alert('提交申请失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {

  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(item => {
        axios.delete(`${apiBaseUrl.value}/${item.ID}`)
        alert('删除成功')
        selectedIds.value = []
      }
      ))
      await searchApplications()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const editApplication = (item) => {
  formData.value = {
    ID: item.ID,
    system_code: item.system_code,
    STAFF_CODE: item.STAFF_CODE,
    STAFF_NAME: item.STAFF_NAME,
    ID_CARD: item.ID_CARD,
    STAFF_GENDER: item.STAFF_GENDER,
    TELEPHONE: item.TELEPHONE,
    STAFF_TYPE: item.STAFF_TYPE,
    AFFILIATION: item.AFFILIATION,
    STAFF_POSITION: item.STAFF_POSITION,
    STAFF_MAJOR: item.STAFF_MAJOR,
    PAPERS: item.PAPERS,
    stamp: item.stamp,
  }
  isEditing.value = true
  isDialogOpen.value = true
}



const toggleSelectAll = () => {
  console.log('触发全选:', !selectAll.value)
  selectAll.value = !selectAll.value
  applications.value.forEach(app => {
    app.selected = selectAll.value
    console.log(`设置 ${app.ID} 的选中状态为:`, app.selected)
  })
}

const toggleItemSelection = (item) => {
  console.log('切换选中状态:', item.ID, !item.selected)
  item.selected = !item.selected
  updateSelectAllState()
}

const updateSelectAllState = () => {

  selectAll.value = applications.value.length > 0 && applications.value.every(app => app.selected)

}




const getStatusClass = (status) => {
  const classMap = {
    '未审核': 'bg-yellow-100 text-yellow-800',
    '已通过': 'bg-green-100 text-green-800',
    '未通过': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

const importFile = ref(null)

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

const importData = () => {
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = '.xlsx, .xls, .csv'
  fileInput.style.display = 'none'

  fileInput.onchange = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = async (e) => {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const jsonData = XLSX.utils.sheet_to_json(worksheet)

      try {
        const response = await axios.post(`${apiBaseUrl.value}/import`, jsonData)
        alert(response.data.message || '导入成功')
        await searchApplications()
      } catch (error) {
        console.error('导入失败:', error)
        alert('导入失败: ' + (error.response?.data?.message || error.message))
      }
    }
    reader.readAsArrayBuffer(file)
  }

  document.body.appendChild(fileInput)
  fileInput.click()
  document.body.removeChild(fileInput)
}



function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}




onMounted(() => {
  searchApplications()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>

